<template>
  <footer class="footer">
    <div class="container">
      <div class="footer-content">
        <!-- 主要信息 -->
        <div class="footer-main">
          <div class="logo-section">
            <div class="logo">
              <img class="logo-icon" src="/logo.png" alt="个人博客" />
              <span class="logo-text">个人博客</span>
            </div>
            <p class="description">
              {{
                footerData.description ||
                "分享我的项目和技术见解，记录前端开发的点滴。"
              }}
            </p>
          </div>

          <div class="links-section" v-if="!loading">
            <!-- 快速链接 -->
            <div
              class="link-group"
              v-if="footerData.quickLinks && footerData.quickLinks.length > 0"
            >
              <h4>{{ footerData.quickLinksTitle || "快速链接" }}</h4>
              <ul>
                <li v-for="link in footerData.quickLinks" :key="link.title">
                  <a :href="link.url" :target="link.target || '_self'">{{
                    link.title
                  }}</a>
                </li>
              </ul>
            </div>

            <!-- 资源 -->
            <div
              class="link-group"
              v-if="footerData.resources && footerData.resources.length > 0"
            >
              <h4>{{ footerData.resourcesTitle || "资源" }}</h4>
              <ul>
                <li
                  v-for="resource in footerData.resources"
                  :key="resource.title"
                >
                  <a
                    :href="resource.url"
                    :target="resource.target || '_blank'"
                    >{{ resource.title }}</a
                  >
                </li>
              </ul>
            </div>

            <!-- 社交媒体 -->
            <div
              class="link-group"
              v-if="footerData.socialMedia && footerData.socialMedia.length > 0"
            >
              <h4>{{ footerData.socialMediaTitle || "社交媒体" }}</h4>
              <div class="social-links">
                <a
                  v-for="social in footerData.socialMedia"
                  :key="social.title"
                  :href="social.url"
                  :target="social.target || '_blank'"
                  class="social-link"
                  :title="social.title"
                >
                  <Icon :name="social.icon" />
                </a>
                <!-- 邮箱链接 -->
                <div
                  v-if="footerData.email"
                  class="email-link"
                  @click="copyEmail"
                  @mouseenter="showEmail = true"
                  @mouseleave="showEmail = false"
                >
                  <div
                    class="social-link"
                    :title="showEmail ? '点击复制邮箱地址' : '邮箱'"
                  >
                    <Icon name="fa:envelope" />
                  </div>
                  <div v-if="showEmail" class="email-tooltip">
                    {{ footerData.email }}
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 加载状态 -->
          <div class="links-section" v-else>
            <div class="link-group">
              <h4>快速链接</h4>
              <ul>
                <li><span class="skeleton">加载中...</span></li>
              </ul>
            </div>
          </div>
        </div>

        <!-- 版权信息 -->
        <div class="footer-bottom">
          <div class="copyright">
            <p>
              &copy; {{ currentYear }} {{ footerData.copyright || "个人博客" }}.
              保留所有权利.
            </p>
          </div>
        </div>
      </div>
    </div>
  </footer>
</template>

<script setup lang="ts">
import { watch } from 'vue';
// 响应式数据
const loading = ref(true);
const showEmail = ref(false);
const analyticsCode = ref<string>("");
const footerData = ref<any>({
  description: "",
  quickLinks: [],
  quickLinksTitle: "快速链接",
  resources: [],
  resourcesTitle: "资源",
  socialMedia: [],
  socialMediaTitle: "社交媒体",
  email: "",
  copyright: "个人博客",
});

// 默认数据，用于API加载失败时的回退
const defaultFooterData = {
  description: "分享我的项目和技术见解，记录前端开发的点滴。",
  quickLinks: [
    { title: "关于我", url: "#about" },
    { title: "项目", url: "#projects" },
    { title: "技能", url: "#skills" },
    { title: "联系", url: "#contact" },
  ],
  quickLinksTitle: "快速链接",
  resources: [
    { title: "开源项目", url: "https://gitee.com/", target: "_blank" },
    { title: "简历", url: "/resume", target: "_blank" },
  ],
  resourcesTitle: "资源",
  socialMedia: [],
  socialMediaTitle: "社交媒体",
  email: "",
  copyright: "个人博客",
};

// 加载统计代码
const loadAnalyticsCode = async () => {
  try {
    const response = await $fetch<{
      success: boolean;
      message: string;
      data: any;
    }>("/api/home/analytics");

    if (response.success && response.data) {
      const data = response.data;
      analyticsCode.value = data.headCode || "";
    }
  } catch (error) {
    console.error("加载统计代码失败:", error);
  }
};

// 加载Footer数据
const loadFooterData = async () => {
  try {
    const response = await $fetch<{
      success: boolean;
      message: string;
      data: any;
    }>("/api/home/footer");

    if (response.success && response.data) {
      // 解析数据
      const data = response.data;

      // 处理快速链接
      let quickLinks = [];
      if (data.quickLinks) {
        try {
          quickLinks =
            typeof data.quickLinks === "string"
              ? JSON.parse(data.quickLinks)
              : data.quickLinks;
        } catch (e) {
          console.error("解析快速链接数据失败:", e);
          quickLinks = defaultFooterData.quickLinks;
        }
      } else {
        quickLinks = defaultFooterData.quickLinks;
      }

      // 处理资源链接
      let resources = [];
      if (data.resources) {
        try {
          resources =
            typeof data.resources === "string"
              ? JSON.parse(data.resources)
              : data.resources;
        } catch (e) {
          console.error("解析资源链接数据失败:", e);
          resources = defaultFooterData.resources;
        }
      } else {
        resources = defaultFooterData.resources;
      }

      // 处理社交媒体链接
      let socialMedia = [];
      if (data.socialMedia) {
        try {
          socialMedia =
            typeof data.socialMedia === "string"
              ? JSON.parse(data.socialMedia)
              : data.socialMedia;
        } catch (e) {
          console.error("解析社交媒体链接数据失败:", e);
          socialMedia = defaultFooterData.socialMedia;
        }
      } else {
        socialMedia = defaultFooterData.socialMedia;
      }

      footerData.value = {
        description: data.description || defaultFooterData.description,
        quickLinks,
        quickLinksTitle:
          data.quickLinksTitle || defaultFooterData.quickLinksTitle,
        resources,
        resourcesTitle: data.resourcesTitle || defaultFooterData.resourcesTitle,
        socialMedia,
        socialMediaTitle:
          data.socialMediaTitle || defaultFooterData.socialMediaTitle,
        email: data.email || defaultFooterData.email,
        copyright: data.copyright || defaultFooterData.copyright,
      };
    } else {
      // 使用默认数据
      footerData.value = { ...defaultFooterData };
    }
  } catch (error) {
    console.error("加载Footer数据失败:", error);
    // 使用默认数据
    footerData.value = { ...defaultFooterData };
  } finally {
    loading.value = false;
  }
};

// 复制邮箱到剪贴板
const copyEmail = async () => {
  try {
    await navigator.clipboard.writeText(
      footerData.value.email || defaultFooterData.email
    );
    // 这里可以添加一个简单的提示，告诉用户已复制
    console.log("邮箱地址已复制到剪贴板");
  } catch (err) {
    console.error("复制失败:", err);
  }
};

// 获取当前年份
const currentYear = new Date().getFullYear();

// 使用 useHead 来添加统计代码
const updateAnalyticsHead = () => {
  if (!analyticsCode.value) return;
  
  // 使用 useHead 来动态添加脚本
  useHead({
    script: [
      {
        innerHTML: analyticsCode.value,
        type: 'text/javascript'
      }
    ]
  });
};

// 页面加载时获取数据
onMounted(() => {
  loadFooterData();
  loadAnalyticsCode().then(() => {
    updateAnalyticsHead();
  });
});

// 监听统计代码变化
watch(analyticsCode, () => {
  updateAnalyticsHead();
});
</script>

<style scoped>
.footer {
  background-color: var(--dark-color);
  color: #ffffff;
  margin-top: auto;
}

.footer-content {
  padding: 3rem 0 1rem;
}

.footer-main {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 3rem;
  margin-bottom: 2rem;
}

.logo-section .logo {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.logo-icon {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
}

.logo-text {
  font-size: 1.25rem;
  font-weight: 600;
}

.description {
  color: #86909c;
  line-height: 1.6;
  max-width: 300px;
}

.links-section {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 2rem;
}

.link-group h4 {
  color: #ffffff;
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 1rem;
}

.link-group ul {
  list-style: none;
}

.link-group ul li {
  margin-bottom: 0.5rem;
}

.link-group ul li a {
  color: #86909c;
  text-decoration: none;
  transition: var(--transition);
}

.link-group ul li a:hover {
  color: var(--primary-color);
}

.social-links {
  display: flex;
  gap: 1rem;
}

.social-link {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 2.5rem;
  height: 2.5rem;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  color: #86909c;
  text-decoration: none;
  transition: var(--transition);
}

.social-link:hover {
  background-color: var(--primary-color);
  color: white;
  transform: translateY(-2px);
}

.email-link {
  position: relative;
}

.email-tooltip {
  position: absolute;
  bottom: calc(100% + 8px);
  left: 50%;
  transform: translateX(-50%);
  background-color: #333;
  color: #fff;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.email-tooltip::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  border: 5px solid transparent;
  border-top-color: #333;
}

.footer-bottom {
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 2rem;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.copyright p {
  color: #86909c;
  font-size: 0.875rem;
}

/* 加载状态样式 */
.skeleton {
  color: #86909c;
  font-style: italic;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .footer-main {
    grid-template-columns: 1fr;
    gap: 2rem;
  }

  .links-section {
    grid-template-columns: 1fr;
    gap: 1.5rem;
  }

  .footer-bottom {
    flex-direction: column;
    gap: 1rem;
    text-align: center;
  }
}

@media (max-width: 480px) {
  .footer-content {
    padding: 2rem 0 1rem;
  }

  .social-links {
    justify-content: center;
  }
}
</style>
